<template>
  <div class="app-container news-container">
    <el-form size="mini" ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left: 50px">
      <el-form-item label="头像：" prop="head_img">
        <div style="padding-left: 3px; position: relative">
          <el-upload class="avatar-uploader" :auto-upload="true" :http-request="(param) => uploadFile(param, 'head_img')" :show-file-list="false" action="string">
            <img v-if="dataForm.head_img" :src="dataForm.head_img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <i class="el-icon-error" v-if="dataForm.head_img" @click="deleteImgFile()" style="position: absolute; top: -5px; left: 115px; color: red; font-size: 15px; cursor: pointer"></i>
        </div>
      </el-form-item>
      <el-form-item label="用户名：" prop="name">
        <el-input v-model="dataForm.name" type="text" />
      </el-form-item>
      <el-form-item label="手机号：">
        <el-input disabled v-model="phone" type="text" />
      </el-form-item>
      <el-form-item label="真实姓名：" prop="create_user">
        <el-input v-model="dataForm.create_user" type="text" />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input v-model="dataForm.email" type="text" />
      </el-form-item>
      <el-form-item label="地址：" prop="zone">
        <el-cascader ref="cascaderHandle" v-model="dataForm.address" :props="{ checkStrictly: true }" :options="cityOptions" @change="areaChangeHandle" style="width: 100%" placeholder="请选择所属地区，可搜索" filterable clearable></el-cascader>
      </el-form-item>
      <el-form-item label="旧密码：">
        <el-input v-model="dataForm.old_password" type="password" />
      </el-form-item>
      <el-form-item label="新密码：">
        <el-input v-model="dataForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码：">
        <el-input v-model="dataForm.newPassword2" type="password" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div style="margin-left: 100px">
      <el-button size="mini" @click="cancel">取消</el-button>
      <el-button size="mini" type="primary" @click="change">确定</el-button>
    </div>
  </div>
</template>

<script>
import city from './city.json'
import QuillEditor from '@/components/VueQuillEditor/quillEditor.vue'
import { upload, getInfo } from '@/api/api.js'
import { savemycenter } from '@/api/mycenter.js'
import { isPassword } from '@/utils/validate.js'
export default {
  name: 'Mycenter',
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value && !isPassword(value)) {
        callback(new Error('密码6~20位 必须含大写字母、小写字母、数字'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value && !isPassword(value)) {
        callback(new Error('密码6~20位 必须含大写字母、小写字母、数字'))
      } else if (value !== this.dataForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      phone: '', // 手机号
      cityOptions: city,
      dataForm: {
        head_img: '', // 头像
        name: '', // 用户名
        create_user: '', // 真实姓名
        email: '', // 邮箱
        address: [], // 地址集合
        zone: '', // 具体地址
        old_password: '', // 旧密码
        password: '', // 新密码
        newPassword2: '', // 确认密码
      },
      rules: {
        name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        create_user: [{ required: true, message: '真实姓名不能为空白', trigger: 'blur' }],
        old_password: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { min: 6, message: '新密码必须大于6', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
        newPassword2: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { min: 6, message: '新密码必须大于6', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' },
        ],
      },
    }
  },
  components: { QuillEditor },
  mounted() {
    console.log('this.$store.state.user.phone')
    this.phone = this.$store.state.user.phone
    getInfo()
      .then((res) => {
        if (res.code == 200) {
          console.log(res.data)
          this.phone = res.data.phone
          this.dataForm.head_img = res.data.head_img // 头像
          this.dataForm.name = res.data.name // 用户名
          this.dataForm.create_user = res.data.create_user // 真实姓名
          this.dataForm.email = res.data.email // 邮箱
          this.dataForm.address = res.data.zone.split('/') // 地址集合
          this.dataForm.zone = res.data.zone // 具体地址
        }
      })
      .catch((response) => {
        this.$notify.error({
          title: '失败',
          message: response.data.errmsg,
        })
      })
  },
  methods: {
    //地址改动事件
    areaChangeHandle() {
      this.$refs.cascaderHandle.dropDownVisible = false
      const zone = this.dataForm.address.join('/')
      this.dataForm.zone = zone
    },
    deleteImgFile() {
      this.dataForm.head_img = ''
    },
    //文件上传
    uploadFile(param, key1) {
      let _this = this
      const formData = new FormData()
      formData.append('file', param.file)
      const fileName = param.file.name
      const lastNum = parseInt(fileName.lastIndexOf('.')) + 1
      const endName = fileName.substring(lastNum).toLowerCase()
      if (endName != 'jpg' && endName != 'png' && endName != 'bmp') {
        this.$message.error('图片格式错误，只支持jpg、png、bmp格式')
        return
      }
      upload(formData)
        .then((res) => {
          if (res.code == 200) {
            const data = res.data
            this.dataForm[key1] = data.url
          }
        })
        .catch((response) => {
          param.onError()
        })
    },
    cancel() {
      this.dataForm = {
        head_img: '', // 头像
        name: '', // 用户名
        create_user: '', // 真实姓名
        email: '', // 邮箱
        address: [], // 地址集合
        zone: '', // 具体地址
        old_password: '', // 旧密码
        password: '', // 新密码
        newPassword2: '', // 确认密码
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    change() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        var that = this
        if (that.dataForm.password.length > 0 && that.dataForm.old_password.length <= 0) {
          // 填写了新密码
          this.$notify.warning({
            title: '警告',
            message: '请填写旧密码',
          })
        } else if (that.dataForm.password.length > 0 && that.dataForm.newPassword2.length <= 0) {
          // 填写了新密码，未重复填写
          this.$notify.warning({
            title: '警告',
            message: '请再次确认密码',
          })
        } else if (that.dataForm.newPassword2.length > 0 && that.dataForm.password.length <= 0) {
          // 填写了确认密码，未填写新密码
          this.$notify.warning({
            title: '警告',
            message: '请天写新密码',
          })
        } else if (that.dataForm.newPassword2.length > 0 && that.dataForm.old_password.length <= 0) {
          // 填写了确认密码。未填写旧密码
          this.$notify.warning({
            title: '警告',
            message: '请天写旧密码',
          })
        } else {
          var parmas = {
            head_img: that.dataForm.head_img, // 头像
            name: that.dataForm.name, // 用户名
            create_user: that.dataForm.create_user, // 真实姓名
            email: that.dataForm.email, // 邮箱
            zone: that.dataForm.zone, // 具体地址
            old_password: that.dataForm.old_password, // 旧密码
            password: that.dataForm.password, // 新密码
          }
          savemycenter(parmas)
            .then((response) => {
              if (response.code == 200) {
                this.$notify.success({
                  title: '成功',
                  message: '个人中心保存成功',
                })
              }
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg,
              })
            })
        }
      })
    },
  },
}
</script>
<style lang="scss">
.news-container {
  .el-dialog__body {
    padding: 0 0 10px 0;
  }
}

.my-btn .el-form-item__content {
  width: 100%;
}

.labelBefore label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
